<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>简单画板</title>
</head>
<body>
<canvas id="myca" width="400px" height="300px" style="border: solid"></canvas>
<script>
    var can=document.getElementById("myca");
    var ctx=can.getContext("2d");
    var mouseDown=false;
    //当前的点
    var mouseX=0;var mouseY=0;
    //先前的点
    var preX=0; var preY=0;
    function onMouseDown(e){
        mouseDown=true;
        preX=e.pageX-can.clientLeft;//教材P.196页的方法
        preY=e.pageY-can.clientTop;
    }
    function onMouseUp(e){
        mouseDown=false;
    }
    function onMouseMove(e){
        if(mouseDown)
        {
            mouseX=e.pageX-can.clientLeft;
            mouseY=e.pageY-can.clientTop;
            ctx.lineWidth=2;
            ctx.beginPath();//★自动平滑
            ctx.moveTo(preX,preY);
            ctx.lineTo(mouseX,mouseY);
            ctx.stroke();
            preX=mouseX;
            preY=mouseY;
        }
    }
    can.addEventListener("mousedown",onMouseDown,false);
    can.addEventListener("mouseup",onMouseUp,false);
    can.addEventListener("mousemove",onMouseMove,false);
</script>
</body>
</html>